package com.mm.cloud.common.security.aspect;

import com.mm.cloud.common.security.annotation.PreAuthorize;
import com.mm.cloud.common.security.exception.AccessDeniedException;
import com.mm.cloud.common.security.helper.LoginUserHelper;
import com.mm.cloud.common.security.loginuser.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PatternMatchUtils;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Set;

/**
 * 自定义权限校验
 *
 * @author mr
 * @since 2021-07-12
 */
@Aspect
@Component
@Order(-1)
public class PreAuthorizeAspect {

    /**
     * 所有权限标识
     */
    private static final String ALL_PERMISSION = "*:*:*";

    /**
     * 数组为0时
     */
    private static final int ARRAY_EMPTY = 0;

    @Pointcut("@annotation(com.mm.cloud.common.security.annotation.PreAuthorize)")
    public void preAuthorize() {
    }

    @Around("preAuthorize()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
        if (annotation == null) {
            return point.proceed();
        }

        if (StringUtils.isNotEmpty(annotation.hasAuthorize())) {
            if (hasAuthorize(annotation.hasAuthorize())) {
                return point.proceed();
            }
            throw new AccessDeniedException();
        } else if (ARRAY_EMPTY < annotation.hasAnyAuthorize().length) {
            if (hasAnyAuthorize(annotation.hasAnyAuthorize())) {
                return point.proceed();
            }
            throw new AccessDeniedException();
        } else if (StringUtils.isNotEmpty(annotation.hasRole())) {
            if (hasRole(annotation.hasRole())) {
                return point.proceed();
            }
            throw new AccessDeniedException();
        } else if (ARRAY_EMPTY < annotation.hasAnyRole().length) {
            if (hasAnyRole(annotation.hasAnyRole())) {
                return point.proceed();
            }
            throw new AccessDeniedException();
        }
        return point.proceed();
    }

    /**
     * 验证用户是否具备某权限
     *
     * @param authorize 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasAuthorize(String authorize) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getAuthorities())) {
            return false;
        }
        return hasAuthorities(loginUser.getAuthorities(), authorize);
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param anyAuthorize 权限集合
     * @return 用户是否具有以下任意一个权限
     */
    public boolean hasAnyAuthorize(String[] anyAuthorize) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getAuthorities())) {
            return false;
        }
        Set<String> authorities = loginUser.getAuthorities();
        for (String authorize : anyAuthorize) {
            if (authorize != null && hasAuthorities(authorities, authorize)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否包含权限
     *
     * @param authorities 权限列表
     * @param authorize 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasAuthorities(Collection<String> authorities, String authorize) {
        return authorities.stream().filter(StringUtils::isNotBlank)
                .anyMatch(x -> ALL_PERMISSION.contains(x) || PatternMatchUtils.simpleMatch(x, authorize));
    }

    /**
     * 判断用户是否拥有某个角色
     *
     * @param role 角色字符串
     * @return 用户是否具备某角色
     */
    public boolean hasRole(String role) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getRoles())) {
            return false;
        }
        for (String roleKey : loginUser.getRoles()) {
            if (roleKey.equals(role)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证用户是否具有以下任意一个角色
     *
     * @param roles 角色集合
     * @return 用户是否具有以下任意一个角色
     */
    public boolean hasAnyRole(String[] roles) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getRoles())) {
            return false;
        }
        for (String role : roles) {
            if (hasRole(role)) {
                return true;
            }
        }
        return false;
    }
}
